package com.dl.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.dl.blog.service.impl.BaiduApiServiceImpl;
import com.dl.dlcommon.utils.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DL
 * @create 2025-07-07 下午9:45
 */
@RestController
@RequestMapping("/api/baidu")
public class BaiduApiController {

    @Autowired
    private BaiduApiServiceImpl baiduApiService;

    /**
     * 记录页面访问
     */
    @GetMapping("/local")
    public Result<?> recordVisit(HttpServletRequest request) {
        // 获取客户端IP
        String clientIp = getClientIp(request);
        System.out.println("clientIp = " + clientIp);
        JSONObject locationByIp = baiduApiService.getLocationByIp(clientIp);
        return Result.success(String.valueOf(locationByIp));
    }

    // 获取客户端真实IP
    private String getClientIp(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader == null) {
            return request.getRemoteAddr();
        }
        return xffHeader.split(",")[0];
    }
}
